package com.jws.jawestshow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
//import android.jws.JwsHardwareManager;
//import android.jws.JwsCard;
import android.widget.Button;
import android.util.Log;
import android.widget.Toast;

import android.content.BroadcastReceiver;

import com.android.jws.JwsIntents;
import com.jws.thirdlibrary.CxManager;

public class WiegandActivity extends Activity {


    private Button mButtonOpen;
    private Button mButtonClose;
    private TextView mCardID;

    private String StrID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wiegand);
        mCardID = (TextView) findViewById(R.id.cardid);
        initButton();
        initDate();
    }

    CxManager mCxManager;

    private void initDate() {
        mCxManager = JawestshowApplication.getCxManager();
    }

    private void initButton() {
        mButtonOpen = (Button) findViewById(R.id.open);
        mButtonClose = (Button) findViewById(R.id.close);
        mButtonOpen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                registerWiegand();
                Toast.makeText(WiegandActivity.this, R.string.jws_open_success, Toast.LENGTH_SHORT).show();
            }
        });

        mButtonClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                unregisterWiegand();
                Toast.makeText(WiegandActivity.this, R.string.jws_close_success, Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void registerWiegand() {
        mWiegandReceiver = new WiegandReceiver();
        IntentFilter intentFilter = new IntentFilter(JwsIntents.REQUEST_RESPONSE_WIEGAND_ID_ACTION);
        registerReceiver(mWiegandReceiver, intentFilter);
        mCxManager.jwsRegisterJwsHardwareWiegListener();
    }

    public void unregisterWiegand() {
        mCxManager.jwsUnregisterJwsHardwareWiegListener();
        if (mWiegandReceiver != null) {
            unregisterReceiver(mWiegandReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterWiegand();
    }

    WiegandReceiver mWiegandReceiver;

    class WiegandReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            StrID = intent.getStringExtra(JwsIntents.EXTRA_WIEGAND_ID_RESPONSE);
            Log.i("byf-wiegand", "onReceive() " + "StrID:  " + StrID);
            mCardID.setText("Card id:" + StrID);
        }
    }

}
